package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.comment.repository.TravelCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {
    @Autowired
    private TravelCommentRepository repository; //crud


    @Autowired
    private MongoTemplate template; //高级查询

    @Override
    public TravelComment saveOrUpdate(TravelComment comment) {
        //添加跟更新
        if(!StringUtils.hasLength(comment.getId())){
            comment.setCreateTime(new Date());
        }
        //处理引用评论,评论的评论
        if(comment.getType()==TravelComment.TRAVLE_COMMENT_TYPE){
            if(StringUtils.hasLength(comment.getRefComment().getId())){
                comment.setRefComment(repository.findById(comment.getRefComment().getId()).get());
            }
        }

        repository.save(comment);
        return comment;
    }

    @Override
    public Page query(TravelCommentQuery qo) {
        //mongodb分页操作
        //只能通过查询他的高查结果，自己封装成page对象
        Query query = new Query();  //分页条件

        //查询条件
        if(qo.getTravelId()!=-1){
            query.addCriteria(Criteria.where("travelId").is(qo.getTravelId()));
        }
        //查询总数  根据这个类来找到文档查询总数
        Long total = template.count(query, TravelComment.class);
        if(total==0){
            Page.empty();  //如果total为null，返回一个空
        }
        //分页条件 根据创建时间倒序分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(),
                Sort.Direction.DESC, "createTime");
        //拼接查询条件
        query.with(pageable);
        //查询所有结果
        List<TravelComment> list = template.find(query, TravelComment.class);
        return new PageImpl(list,pageable,total);  //实现分页方法
    }

    @Override
    public long getCount(Long travelId) {
        Query query = new Query();  //分页条件
        //查询条件
        query.addCriteria(Criteria.where("travelId").is(travelId));
        return template.count(query, TravelComment.class);
    }
}
